package com.example.demo;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import jakarta.websocket.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@ClientEndpoint
public class AllClientEndpoint {
    private Session session;
    private CountDownLatch latch = new CountDownLatch(1);
    private String lastMessage;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        System.out.println("✅ 连接已建立，连接到: " + session.getRequestURI());
        latch.countDown(); // 通知主线程连接成功
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("📨 收到消息: " + message);
        this.lastMessage = message;
        // 这里可以处理收到的消息，比如解析JSON等
        try {
            int i = Integer.parseInt(message);
            System.out.println(sendSzdxlxDir.getCurSj() + "<==onMessage==>" + i);
            if (i < 7200) {
                sendSzdxlxDir.setCurSj(i);
                save();
            }
        } catch (Exception e) {
            END = true;
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        System.out.println("❌ 连接关闭: " + closeReason.getReasonPhrase());
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.err.println("💥 发生错误:");
        throwable.printStackTrace();
    }

    // 发送消息的方法
    public void sendMessage(String message) throws IOException {
        if (session != null && session.isOpen()) {
            session.getBasicRemote().sendText(message);
            System.out.println("📤 已发送: " + message);
        } else {
            System.err.println("无法发送消息，会话未打开");
        }
    }

    // 等待连接建立
    public boolean awaitConnection(long timeout, TimeUnit unit) throws InterruptedException {
        return latch.await(timeout, unit);
    }

    // 获取最后一次收到的消息（用于测试或简单交互）
    public String getLastMessage() {
        return lastMessage;
    }

    // 关闭连接
    public void close() throws IOException {
        if (session != null) {
            session.close();
        }
    }

    private static final String PHPSESSID = "elo4eljvrepfh5vgf0cs6i1l44";
    private static boolean END = false;
    private static final String CONFIG_PATH = "D:\\develop\\java\\sydata\\demo\\demo\\src\\main\\resources\\allKcmx.json";
    private static List<SzdxlxDir> szdxlxDirs;
    private static final int JG = 6;
    private static SzdxlxDir curSzdxlxDir;
    private static SzdxlxDir sendSzdxlxDir;

    private static void load() {
        szdxlxDirs = JSON.parseArray(FileUtil.readString(CONFIG_PATH, CharsetUtil.UTF_8), SzdxlxDir.class);
        nextSzdxlxDir();
    }

    private static void nextSzdxlxDir() {
        for (SzdxlxDir szdxlxDir : szdxlxDirs) {
            if (szdxlxDir.getCurSj() != szdxlxDir.getMaxSj()) {
                curSzdxlxDir = szdxlxDir;
                break;
            }
        }
    }

    private static void save() {
        FileUtil.writeString(JSON.toJSONString(szdxlxDirs, JSONWriter.Feature.PrettyFormat), CONFIG_PATH, CharsetUtil.UTF_8);
    }

    public static void main(String[] args) {
        load();
        if (curSzdxlxDir == null) {
            return;
        }
        loadUserlog();
        // 要连接的 WebSocket 服务地址 (以 wss://echo.websocket.org 为例，这是一个公共测试服务)
        String serverUrl = "wss://sdckwss.5zk.com.cn/sdck_jjsp?session_id=" + PHPSESSID;
        AllClientEndpoint clientEndpoint = new AllClientEndpoint();
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        try {
            System.out.println("🔄 正在连接到: " + serverUrl);
            // 连接服务器
            container.connectToServer(clientEndpoint, new URI(serverUrl));
            // 等待连接建立（最多等5秒）
            if (clientEndpoint.awaitConnection(5, TimeUnit.SECONDS)) {
                System.out.println("✅ 成功连接到服务器！");
                while (!END) {
                    Thread.sleep(JG * 1000L);
                    curSzdxlxDir.setCurSj(Math.min(curSzdxlxDir.getMaxSj(), curSzdxlxDir.getCurSj() + JG));
                    sendSzdxlxDir = curSzdxlxDir;
                    clientEndpoint.sendMessage("Update1: jjwikiid=" + curSzdxlxDir.getJjwikiid() + "&TypeId=" + curSzdxlxDir.getTypeId() + "&cur_jindu=" + curSzdxlxDir.getCurSj() + "&userlog_id=" + curSzdxlxDir.getUserLogId());
                    if (curSzdxlxDir.getCurSj() >= curSzdxlxDir.getMaxSj()) {
                        nextSzdxlxDir();
                        if (curSzdxlxDir != null) {
                            loadUserlog();
                        } else {
                            END = true;
                        }
                    }
                }

//                Thread.sleep(JG * 1000L);
//                // 关闭连接
//                clientEndpoint.close();

            } else {
                System.err.println("连接超时");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void loadUserlog() {
        String url = "https://stu.5zk.com.cn/zk8exam/jp_wiki_study.php?kcdm=" + curSzdxlxDir.getKcdm() + "&jjwikiid=" + curSzdxlxDir.getJjwikiid();
        System.out.println(url);
        HttpRequest get = HttpUtil.createGet(url);
        get.cookie("PHPSESSID=" + PHPSESSID);
        Document document = Jsoup.parse(get.execute().body());
        curSzdxlxDir.setUserLogId(document.getElementById("userlog_id").val());
        System.out.println("获取到userlog_id：" + curSzdxlxDir.getUserLogId());

//        Elements elements = document.select(" .block-content ul li ");
//        List<String> list = new ArrayList<>();
//        for (Element element : elements) {
//            String href = element.selectFirst("a").attr("href");
//            if (StrUtil.isNotBlank(href)) {
//                if (href.endsWith(curSzdxlxDir.getCurJjwikiid())) {
//                    String div = element.select("div").get(1).text();
//                    String[] timeArr = StrUtil.subBetween(div, "/", ")").split(":");
//                    int total = Integer.parseInt(timeArr[0]) * 3600 + Integer.parseInt(timeArr[1]) * 60 + Integer.parseInt(timeArr[2]);
//                    curSzdxlxDir.setMaxSj(total);
//                    System.out.println("获取到视频时长：" + config.getMaxSj());
//                }
//                list.add(StrUtil.subAfter(href, "=", true));
//            }
//        }
        save();
    }
}
